package com.yixuan.mt.common.service.impl;

import com.yixuan.mt.common.local.buckets.BucketsMeta;
import com.yixuan.mt.common.constant.BucketsConstant;
import com.yixuan.mt.common.entity.Bucket;
import com.yixuan.mt.common.local.objects.ObjectsIndex;
import com.yixuan.mt.common.service.BucketsService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class BucketsServiceImpl implements BucketsService {
    @Override
    public void postBuckets(String bucketName) throws IOException {
        BucketsMeta.addToGlobalBucketMeta(bucketName);
        // 创建本地元数据文件
        BucketsMeta.createLocalBucketMeta(bucketName);
        /* 添加基本元数据 */
        // 1.添加创建时间
        // 创建DateTimeFormatter对象，指定目标格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();

        // 格式化当前日期时间
        String formattedDate = now.format(formatter);

        // 创建对象索引文件
        ObjectsIndex.createObjectsIndexFile(bucketName);

        BucketsMeta.addStringToLocalBucketMeta(bucketName, formattedDate);

        // 2.添加访问策略
        BucketsMeta.addConstantToLocalBucketMeta(bucketName, (byte) BucketsConstant.BUCKET_DEFAULT_ACCESS_POLICY);
        // 3.添加对象数量
        BucketsMeta.addIntToLocalBucketMeta(bucketName, 0);
    }

    @Override
    public void deleteBuckets(String bucketName) {

    }

    @Override
    public void putBuckets(Bucket bucket) {

    }

    @Override
    public List<Bucket> getBuckets() throws IOException {
        List<Bucket> bucketBasicInfoList = new ArrayList<>();
        // 获取所有存储桶名称
        String[] bucketList = BucketsMeta.getBucketListInGlobalMeta();
        if (bucketList[0].isEmpty()) {
            return bucketBasicInfoList;
        }

        // 获取所有桶基本信息
        for (String bucketName : bucketList) {
            bucketBasicInfoList.add(BucketsMeta.getBasicInfoInLocalBucketMeta(bucketName));
        }
        return bucketBasicInfoList;
    }

    @Override
    public Bucket getBucketsSummary(String bucketName) {
        return null;
    }
}
